from flask import Blueprint, jsonify, g, current_app
from flask_restful import Api, Resource, marshal, reqparse
from models.my_fields import channel_fields, news_fields, user_fields, comment_fields

from models.model import Channel, User, db, News, Collect, Comment
from apps.user import require_login
from apps.user import login_gz

news_bp = Blueprint("news_bp", __name__, url_prefix="/news")

api = Api(news_bp)


@news_bp.before_request
def login_gz2():
    login_gz()


# 频道的类试图
class ChannelView(Resource):
    @require_login
    def get(self):
        uid = g.user["user_id"]
        # 获取所有频道
        channel_all = Channel.query.filter(Channel.is_show == True).order_by(Channel.score.desc()).all()

        # 获取当前用户的所有频道
        user_info = User.query.filter(User.uid == uid).first()
        channel_list = user_info.channels

        c_list = []
        for c in channel_all:
            if c not in channel_list:
                c_list.append(c)

        channel_json = marshal(c_list, channel_fields)

        return jsonify({
            "code": 200,
            "msg": "频道获取成功",
            "channel": channel_json,
        })


# 用户频道的类试图
class UserChannelView(Resource):

    # 增加用户的频道
    @require_login
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("cid", type=int, required=True)
        args = req.parse_args()

        cid = args["cid"]  # 频道ID
        uid = g.user["user_id"]

        # 判断一下数据库是否已经有这条数据
        user_info = User.query.filter(User.uid == uid).first()

        # 当前数据库没有要添加的频道
        channel_info = Channel.query.filter(Channel.cid == cid).first()

        if channel_info in user_info.channels:
            return jsonify({
                "code": 200,
                "msg": "已存在"
            })

        user_info.channels.append(channel_info)
        db.session.commit()

        return jsonify({
            "code": 200,
            "msg": "添加成功"
        })

    # 删除用户频道
    @require_login
    def delete(self):
        req = reqparse.RequestParser()
        req.add_argument("cid", type=int, required=True)
        args = req.parse_args()

        cid = args["cid"]  # 频道ID
        uid = g.user["user_id"]

        user_info = User.query.filter(User.uid == uid).first()
        channel_info = Channel.query.filter(Channel.cid == cid).first()

        if channel_info not in user_info.channels:
            return jsonify({
                "code": 400,
                "msg": "该频道不存在"
            })

        # 把中间表的一行数据删除掉
        user_info.channels.remove(channel_info)
        db.session.commit()

        return jsonify({
            "code": 200,
            "msg": "删除成功"
        })

    # 获取用户下的所有频道
    @require_login
    def get(self):
        uid = g.user["user_id"]

        # 通过uid查询当前用户信息
        user_info = User.query.filter(User.uid == uid).first()
        user_channel = user_info.channels

        c_json = marshal(user_channel, channel_fields)

        return jsonify({
            "code": 200,
            "msg": "用户频道获取成功",
            "channels": c_json,
        })


# 资讯的类试图
class IndexChannelView(Resource):
    def get(self):
        # 假设，一共有1000条数据，1-1000，每页10条，那么第5页的数据应该是多少
        # (n-1)*10+1,n*10
        req = reqparse.RequestParser()
        req.add_argument("page", type=int, default=1)
        req.add_argument("limit", type=int, default=10)

        args = req.parse_args()

        begin = (args["page"] - 1) * args["limit"]

        news_list = News.query.order_by(News.read_count.desc()).offset(begin).limit(args["limit"]).all()

        news_all = []
        for item in news_list:
            news_json = marshal(item, news_fields)
            user_info = item.user
            user_json = marshal(user_info, user_fields)
            news_json["user"] = user_json

            news_all.append(news_json)

        return jsonify({
            "code": 200,
            "msg": "推荐资讯信息获取成功",
            "news": news_all
        })


class ChannelNewsView(Resource):
    def get(self, cid):
        # # 获取频道
        # channel_info = Channel.query.filter(Channel.cid == cid).first()
        #
        # # 通过频道信息，获取频道下的所有资讯
        # news_list = channel_info.news

        req = reqparse.RequestParser()
        req.add_argument("page", type=int, default=1)
        req.add_argument("limit", type=int, default=10)

        args = req.parse_args()

        begin = (args["page"] - 1) * args["limit"]

        news_list = News.query.filter(News.channel_id == cid).offset(begin).limit(args["limit"]).all()

        news_all = []
        for item in news_list:
            news_json = marshal(item, news_fields)
            user_info = item.user
            user_json = marshal(user_info, user_fields)
            news_json["user"] = user_json

            news_all.append(news_json)

        return jsonify({
            "code": 200,
            "msg": "当前频道下的资讯获取成功",
            "news": news_all
        })


# 资讯的类试图
class NewsView(Resource):
    @require_login
    def get(self, nid):
        uid = g.user["user_id"]
        # news_info = News.query.filter(News.nid == nid).first()
        news_info = News.query.get(nid)
        news_json = marshal(news_info, news_fields)
        user_json = marshal(news_info.user, user_fields)
        user_json["img"] = current_app.config["QINIU_HOST"] + user_json["img"]

        is_collect = False
        # 判断当前用户是否收藏此文章
        collect_info = Collect.query.filter(Collect.user_id == uid).filter(Collect.news_id == nid).filter(
            Collect.is_delete == 0).first()
        if collect_info:
            # 说明当前用户已经收藏
            is_collect = True

        # 获取当前文章的收藏数
        count = Collect.query.filter(Collect.news_id == nid).filter(Collect.is_delete == 0).count()

        # 获取当前资讯的评论数
        comm_count = Comment.query.filter(Comment.news_id == nid).filter(Comment.status == 0).count()

        return jsonify({
            "code": 200,
            "msg": "资讯信息获取成功",
            "info": {
                "news": news_json,
                "user": user_json,
                "collect": {
                    "status": is_collect,
                    "count": count,
                },
                "comment": {
                    "count": comm_count
                }
            }
        })

    @require_login
    def put(self, nid):
        news_info = News.query.get(nid)

        news_info.read_count += 1

        db.session.commit()

        return jsonify({
            "code": "200",
            "msg": "ok"
        })


# 收藏的类试图
class CollectView(Resource):
    @require_login
    def get(self, nid):
        uid = g.user["user_id"]
        collect_list = Collect.query.filter(Collect.user_id == uid).filter(Collect.is_delete == 0).all()
        news_all = []
        for c in collect_list:
            news_all.append(c.news)

        n_all = []
        for item in news_all:
            news_json = marshal(item, news_fields)
            user_info = item.user
            user_json = marshal(user_info, user_fields)
            news_json["user"] = user_json

            n_all.append(news_json)

        return jsonify({
            "code": 200,
            "msg": "收藏的资讯获取成功",
            "list": n_all
        })

    @require_login
    def post(self, nid):
        uid = g.user["user_id"]
        # 判断一下当前用户当前ID是否已经在表里面了
        collect_info = Collect.query.filter(Collect.user_id == uid).filter(Collect.news_id == nid).first()

        # 如果说在的话，把他的is_delete状态改为0
        if collect_info:
            collect_info.is_delete = 0  # 修改数据
            db.session.commit()
            return jsonify({
                "code": "200",
                "msg": "收藏成功"
            })
        # 如果说不在的话，新写入一条数据，并且使is_delete的状态为0
        c = Collect(user_id=uid, news_id=nid, is_delete=0)
        db.session.add(c)
        db.session.commit()

        return jsonify({
            "code": "200",
            "msg": "收藏成功"
        })

    @require_login
    def delete(self, nid):
        uid = g.user["user_id"]

        collect_info = Collect.query.filter(Collect.news_id == nid).filter(Collect.user_id == uid).first()
        if not collect_info:  # 判断为假说明数据库压根没有这条数据
            return jsonify({
                "code": 400,
                "msg": "您还没有收藏"
            })
        if collect_info.is_delete == 1:
            return jsonify({
                "code": 400,
                "msg": "您还没有收藏"
            })

        collect_info.is_delete = 1
        db.session.commit()
        return jsonify({
            "code": 200,
            "msg": "取消收藏成功"
        })

    @require_login
    def put(self, nid):
        uid = g.user["user_id"]
        collect_info = Collect.query.filter(Collect.news_id == nid).filter(Collect.user_id == uid).first()

        if not collect_info:  # 数据库不存在这条数据，当前应该是没有收藏状态，那就要去收藏
            c = Collect(news_id=nid, user_id=uid, is_delete=0)
            db.session.add(c)
            db.session.commit()

            return jsonify({
                "code": 200,
                "msg": "收藏成功"
            })

        if collect_info.is_delete == 0:  # 说明是已收藏
            collect_info.is_delete = 1
            db.session.commit()
            return jsonify({
                "code": 200,
                "msg": "取消收藏成功"
            })

        collect_info.is_delete = 0
        db.session.commit()

        return jsonify({
            "code": 200,
            "msg": "收藏成功"
        })


# 评论的类试图
class CommentView(Resource):
    @require_login
    def post(self):
        user_id = g.user["user_id"]
        req = reqparse.RequestParser()
        req.add_argument("nid", type=int, required=True)
        req.add_argument("content", type=str, required=True)

        args = req.parse_args()

        # 把数据写入数据库
        c = Comment(user_id=user_id, news_id=args["nid"], content=args["content"])
        db.session.add(c)
        db.session.commit()

        return jsonify({
            "code": 200,
            "msg": "评论成功"
        })

    def get(self):
        req = reqparse.RequestParser()
        req.add_argument("nid", type=int, required=True)
        args = req.parse_args()

        # TODO 分页自行实现

        comment_list = Comment.query.filter(Comment.news_id == args["nid"]).filter(Comment.status == 0).order_by(
            Comment.is_top.desc()).all()

        list = []
        for comm in comment_list:
            comm_json = marshal(comm, comment_fields)
            user_json = marshal(comm.user, user_fields)
            user_json["img"] = current_app.config["QINIU_HOST"] + user_json["img"]

            list.append({
                "comm": comm_json,
                "user": user_json
            })

        return jsonify({
            "code": 200,
            "msg": "评论获取成功",
            "list": list
        })

    @require_login
    def delete(self):
        user_id = g.user["user_id"]
        req = reqparse.RequestParser()
        req.add_argument("cmid", type=int, required=True)
        args = req.parse_args()

        comment_info = Comment.query.filter(Comment.cmid == args["cmid"]).filter(Comment.status == 0).first()
        if not comment_info:
            return jsonify({
                "code": 400,
                "msg": "评论不存在"
            })

        if comment_info.user_id != user_id:
            return jsonify({
                "code": 400,
                "msg": "没有权限"
            })

        comment_info.status = 1
        db.session.commit()

        return jsonify({
            "code": 200,
            "msg": "删除成功"
        })


# 推荐频道
api.add_resource(ChannelView, "/channel")

# 用户频道
api.add_resource(UserChannelView, "/channel/user")

# 资讯列表
api.add_resource(IndexChannelView, "/index/news")

# 推荐的资讯列表
api.add_resource(ChannelNewsView, "/channel/<int:cid>")

# 资讯
api.add_resource(NewsView, "/info/<int:nid>")

# 收藏
api.add_resource(CollectView, "/collect/<int:nid>")

# 评论
api.add_resource(CommentView, "/comment")
